package com.sds.sweng.swat.miplatform.ui.design.parts.area.sub;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.gef.EditPolicy;

import com.sds.sweng.swat.miplatform.ui.design.layouts.EasyGridLayout;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.TableCellSubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.TableSubArea;
import com.sds.sweng.swat.miplatform.ui.design.policies.TableLayoutEditPolicy;

public class TableSubAreaPart extends SubAreaPart {

	protected IFigure createFigure() {
		Label f = (Label) super.createFigure();
		drawChildren(f);

		return f;
	}

	private void drawChildren(Label parent) {
		int subAreaWidth = getAreaWidth();
		int contentsHeight = TableCellSubArea.DEFALT_HEIGHT;

		TableSubArea area = (TableSubArea) getModel();

		int numColumns = area.getTable().getColumns().size();

		if (numColumns > 0) {
			parent.setText("");

			if (parent.getLayoutManager() == null)
				parent.setLayoutManager(EasyGridLayout.create(numColumns, false, 0, 0, 0, 0));

			if (getChildren().size() > 0) {
				contentsHeight = 2;
				int prevRow = -1;

				for (TableCellSubArea tableCell : area.getTable().getTableCells()) {
					if (prevRow != tableCell.getRow()) {
						contentsHeight += tableCell.getHeight();
						prevRow = tableCell.getRow();
					}
				}
			}

			parent.setSize(subAreaWidth, contentsHeight);
		} else {
			parent.setText(area.getName());
			parent.setLayoutManager(null);
			parent.setSize(subAreaWidth, contentsHeight);
		}

		area.setHeight(contentsHeight);
	}

	protected void createEditPolicies() {
		super.createEditPolicies();

		installEditPolicy(EditPolicy.LAYOUT_ROLE, new TableLayoutEditPolicy());
	}

	protected void refreshVisuals() {
		drawChildren((Label) getFigure());
	}

	public void refreshAll() {
		//refreshChildren();
		refreshVisuals();

		getFigure().revalidate();

		((SubAreaContainerPart) getParent()).resizeFigure();
	}

}
